package com.example.homemodule.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.examination.mlib.constants.KitArouterConstants;
import com.example.homemodule.R;
import com.example.homemodule.databinding.DoctorHealthDataBinding;
import com.example.homemodule.model.DoctorHealthModel;
import com.example.homemodule.model.bean.DoctorHealthBean;
import com.example.homemodule.model.bean.ThumbsUpBean;
import com.example.homemodule.utils.HomeUtils;
import com.yilijk.base.base.BaseViewModel;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.LoadingUtils;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import crossoverone.statuslib.StatusUtil;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class DoctorHealthViewModel extends BaseViewModel<DoctorHealthModel> {

    class DoctorHealthHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                ALog.e("点赞成功"+msg.obj);
                data.setThumbs(data.getThumbs()+thumbs);
                doThumbsUp(data.getId(),thumbs);
            }
            thumbs = 0;
        }
    }


    private final String LOG_TAG = DoctorHealthViewModel.class.getSimpleName();
    private Activity mContext;
    private DoctorHealthDataBinding mBinding;
    DoctorHealthBean.DataBean data;

    int thumbs = 0;
    long lastClickThumbs = 0;
    Message message;
    private DoctorHealthHandler doctorHealthHandler;

    public DoctorHealthViewModel(@NonNull Application application) {
        super(application);
    }
    private boolean isOpenGoodAt = false;
    @Override
    public void createRepository() {
        repository = new DoctorHealthModel();
        super.createRepository();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
    }

    public void initViewModel(Activity context,DoctorHealthDataBinding binding){
        this.mBinding = binding;
        this.mContext = context;
    }

    public void initView(){
        StatusUtil.setSystemStatus(mContext,false,true);
        StatusUtil.setUseStatusBarColor(mContext,mContext.getResources().getColor(R.color.white));
    }

    public void initData(int id){
        doctorHealthHandler = new DoctorHealthHandler();
        LoadingUtils.getLoadingUtils(mContext).showLoading();
        getRepository().articleDetail(id, new HttpCallBack<DoctorHealthBean>() {
            @Override
            public void onSuccess(DoctorHealthBean s, int i) {
                if (s.isResult()){
                    mBinding.doctorHealthNsv.setVisibility(View.VISIBLE);
                    mBinding.doctorHealthNull.setVisibility(View.GONE);
                    data = s.getData();
                    if (data!=null){
                        if (data.getHealthNumberDoctorInfo() == null || data.getHealthNumberDoctorInfo().isCancellation()){
                            mBinding.healthDoctorCardInfo.setVisibility(View.GONE);
                        }else{
                            mBinding.healthDoctorCardInfo.setVisibility(View.VISIBLE);
                            Glide.with(mContext).load(data.getHealthNumberDoctorInfo().getAvatar())
                                    .transform(new CenterCrop(),new CircleCrop())
                                    .into(mBinding.doctorHealthAvator);
                            mBinding.doctorHealthName.setText(data.getHealthNumberDoctorInfo().getName());
                            mBinding.doctorHealthTitleName.setText(data.getHealthNumberDoctorInfo().getTitleName());
                            mBinding.doctorHealthHospital.setText(data.getHealthNumberDoctorInfo().getHospitalName() + " " + data.getHealthNumberDoctorInfo().getDepartmentName());
                            mBinding.doctorHealthGoodAt.setText(data.getHealthNumberDoctorInfo() != null && !TextUtils.isEmpty(data.getHealthNumberDoctorInfo().getDescription()) ? "\t\t\t"+data.getHealthNumberDoctorInfo().getDescription() : "\t\t\tnull");

                        }
                        mBinding.doctorHealthTitle.setText(data.getArticleTitle());
                        mBinding.doctorHealthSource.setText(data.getSource() == 1 ? "原创" : "转载");
                        mBinding.doctorHealthArticelExt.setText(data.getSource() == 1 ?
                                "版权说明：@本文版权归【"+data.getHealthNumberDoctorInfo().getName()+"】所有，任何形式转载请联系作者"
                                :
                                "版权说明：本文转载自网络，如有侵权请联系作者删除");
                        mBinding.doctorHealthSource.setBackgroundResource(data.getSource() == 1 ? R.drawable.style_health_ycbg : R.color.white);
                        mBinding.doctorHealthTime.setText(data.getPublishTime());
                        RichText.from(data.getContent()).bind(this)
                        .showBorder(false)
                        .size(ImageHolder.MATCH_PARENT, ImageHolder.WRAP_CONTENT)
                        .into(mBinding.doctorHealthContent);
                        mBinding.doctorHealthGood.setImageResource(data.getThumbsUp()== 1 ? R.mipmap.icon_health_good:R.mipmap.icon_health_ungood);
                        mBinding.doctorHealthGoodtxt.setText("有帮助 "+ (data.getThumbs()>0?data.getThumbs()>999?"999+":data.getThumbs():""));
                        mBinding.doctorHealthGoodtxt.setTextColor(data.getThumbsUp()== 1 ? mContext.getResources().getColor(R.color.new_theme):mContext.getResources().getColor(R.color.color_333));
                    }else{
                        mBinding.doctorHealthNsv.setVisibility(View.GONE);
                        mBinding.doctorHealthNull.setVisibility(View.VISIBLE);
                        mBinding.doctorHealthNullTxt.setVisibility(View.VISIBLE);
                        mBinding.doctorHealthLoadTxt.setVisibility(View.GONE);
                    }
                }else{
                    mBinding.doctorHealthNsv.setVisibility(View.GONE);
                    mBinding.doctorHealthNull.setVisibility(View.VISIBLE);
                    mBinding.doctorHealthNullTxt.setVisibility(View.VISIBLE);
                    mBinding.doctorHealthLoadTxt.setVisibility(View.GONE);
                }
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                mBinding.doctorHealthNsv.setVisibility(View.GONE);
                mBinding.doctorHealthNull.setVisibility(View.VISIBLE);
                mBinding.doctorHealthNullTxt.setVisibility(View.VISIBLE);
                mBinding.doctorHealthLoadTxt.setVisibility(View.GONE);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initListener(){

        //擅长简介点击
        mBinding.doctorHealthMore.setOnClickListener(v -> {
            toDoctorStudio();
        });
        //擅长简介点击
        mBinding.doctorHealthGoodAt.setOnClickListener(v -> {
            toDoctorStudio();
        });

        //去问诊按钮点击跳转工作室
        mBinding.doctorHealthToquiry.setOnClickListener(v -> {
            toDoctorStudio();


        });

        mBinding.doctorHealthNsv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                mBinding.doctorHealthBottomV.setVisibility(View.VISIBLE);
            }
        });

        mBinding.doctorHealthLookOther.setOnClickListener(v -> {
            mContext.finish();
        });
        mBinding.doctorHealthDoGood.setOnClickListener(v -> {
            if (data == null){
                return;
            }
            //每次点赞本地缓存点赞次数
            thumbs ++ ;
            mBinding.doctorHealthGoodtxt.setText("有帮助 "+ ((data.getThumbs()>999 || (data.getThumbs()+thumbs) > 999)  ? "999+":""+(data.getThumbs()+thumbs)));
            mBinding.doctorHealthGoodtxt.setTextColor(mContext.getResources().getColor(R.color.new_theme));
            mBinding.doctorHealthGood.setImageResource(R.mipmap.icon_health_good);
            //如果上次点赞距离当前超过1000ms 统计一次数据
            long l = System.currentTimeMillis();
            if (l-lastClickThumbs < 1000){
                doctorHealthHandler.removeCallbacksAndMessages(null);
            }
            lastClickThumbs = l;
            message = new Message();
            message.what = 1;
            message.obj = thumbs;
            doctorHealthHandler.sendMessageDelayed(message,1000);
            data.setThumbsUp(1);
//            if (data.getThumbsUp() == 1){
//                doThumbsDown(data.getId());
//            }else{
//
//            }
        });
    }

    private void toDoctorStudio() {
        if (data != null && data.getHealthNumberDoctorInfo() != null) {
            HomeUtils.getHomeUtil(mContext)
                    .jumpNativePage_DoctorStudio(data.getHealthNumberDoctorInfo().getPassportId(),"ysjkh",1,1);
        } else {
            ALog.e(LOG_TAG, "data == null || data.getHealthNumberDoctorInfo() == null");
        }
    }

    void doThumbsUp(int id){
        getRepository().thumbsUp(id,0, new HttpCallBack<ThumbsUpBean>() {
            @Override
            public void onSuccess(ThumbsUpBean s, int i) {
                if (s.isResult() && s.getData()!=null){
                    refreshGoodUi();
                }
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }
        });
    }
    void doThumbsUp(int id, int thumbs) {
        getRepository().thumbsUp(id,thumbs, new HttpCallBack<ThumbsUpBean>() {
            @Override
            public void onSuccess(ThumbsUpBean s, int i) {
                if (s.isResult() && s.getData() != null) {
                    data.setThumbsUp(s.getData().getThumbsUp());
                    data.setThumbs(s.getData().getThumbs());
                    refreshGoodUi();
                }
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                data.setThumbsUp(data.getThumbs() - thumbs);
                refreshGoodUi();
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();

            }
        });
    }

    void doThumbsDown(int id){
        getRepository().thumbsdown(id, new HttpCallBack<ThumbsUpBean>() {
            @Override
            public void onSuccess(ThumbsUpBean s, int i) {
                if (s.isResult() && s.getData()!=null){
                    refreshGoodUi();
                       }
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
            }
        });
    }

    void refreshGoodUi(){
        mBinding.doctorHealthGood.setImageResource(data.getThumbsUp()== 1 ? R.mipmap.icon_health_good:R.mipmap.icon_health_ungood);
        mBinding.doctorHealthGoodtxt.setText("有帮助 "+ (data.getThumbs()>0?data.getThumbs()>999?"999+":data.getThumbs():""));
        mBinding.doctorHealthGoodtxt.setTextColor(data.getThumbsUp()== 1 ? mContext.getResources().getColor(R.color.new_theme):mContext.getResources().getColor(R.color.color_333));
    }
}

